package com.swak.reactivex.threads;

import com.swak.utils.Ints;

public class MultiTaskQueue implements Queue {

	private final ThreadLocal<Record> holder = new ThreadLocal<Record>() {
		@Override
		protected Record initialValue() {
			return new Record();
		}
	};

	final int multi;
	final TaskQueue[] multis;

	public MultiTaskQueue(int multi) {
		this.multi = multi;
		multis = new TaskQueue[multi];
		for (int i = 0; i < multi; i++) {
			multis[i] = new TaskQueue();
		}
	}

	@Override
	public void execute(Runnable task, Context executor) {
		holder.get().next().execute(task, executor);
	}

	@Override
	public void shutdown() {
		for (TaskQueue queue : multis) {
			queue.shutdown();
		}
	}

	@Override
	public void shutdownNow() {
		for (TaskQueue queue : multis) {
			queue.shutdownNow();
		}
	}

	class Record {
		int index = Ints.random(multi);

		TaskQueue next() {
			TaskQueue next = multis[index++ % multi];
			if (index >= multi) {
				index = 0;
			}
			return next;
		}
	}
}
